
/* Generated by Interface Builder */

#import "DocApp.h"
#import "Document.h"
#import <appkit/defaults.h>
#import <appkit/Application.h>
#import <appkit/Window.h>
#import <appkit/Text.h>
#import <appkit/ScrollView.h>
#import <appkit/Cursor.h>
#import <appkit/SavePanel.h>
#import <streams/streams.h>
#import <string.h>
#import <sys/file.h>

@implementation Document

+ new
{
	self = [super new];
	if (![NXApp loadNibSection:"Document.nib" owner:self]) {
		[self free];
		return nil;
	}
	[self setName:"Untitled"];
	[[document window] setDelegate:self];
	[[document docView] setDelegate:self];
	[[document window] makeKeyAndOrderFront:self];
	
	return self;
}

+ newFromFile:(const char *)fileName
{
	NXStream	*st;
	
	if (st = NXMapFile(fileName, NX_READONLY)) {
		self = [self new];
		[NXWait push];
		[[document docView] readText: st];
		[document display];
		[self setName:fileName];
		NXCloseMemory (st, NX_FREEBUFFER);
		[NXWait pop];
		return self;
	} else {
		return nil;
	}
}

- save:sender 
{
    const char *fileName = [self name];

    if ((fileName == NULL) ||
	(strcmp (fileName, "Untitled") == 0) || (strcmp (fileName, "") == 0)) {
      if ([[NXApp savePanel] runModalForDirectory:"." file:"Untitled"] == NO) 
	return (self);
      else
	fileName = [[NXApp savePanel] filename];
    }

    if (fileName) [self saveDocument:fileName];
  
    return self;
}

- saveAs:sender 
{
    if ([[NXApp savePanel] runModalForDirectory:"." file:[self name]]) 
    	[self saveDocument:[[NXApp savePanel] filename]];

    return self;
}

- setDocument:anObject
{
    document = anObject;
    return self;
}

- saveDocument:(const char *)fileName
{
    BOOL saveOK;
    int fd;
    NXStream *stream = NULL;

    [NXWait push];
    if (saveOK = 
	  (((fd = open (fileName, O_WRONLY|O_CREAT|O_TRUNC, 0644)) != -1) &&
            (stream = NXOpenFile (fd, NX_WRITEONLY))))
	[[document docView] writeText:stream];
    if (stream) NXClose (stream);
    if (fd != -1) close (fd);
    [NXWait pop];

    if (saveOK) {
      	[self setName:fileName];
	[[document window] setDocEdited:NO];
    } else NXRunAlertPanel (NULL, "Can't write file.", "OK", NULL, NULL);

    return self;
}

- setName:(const char *)documentName
{
    [[document window] setTitle:documentName];
    return self;
}

-(const char *)name
{
    return [[document window] title];
}

- text:text isEmpty:(BOOL)empty
{
    if (![[document window] isDocEdited]) 
    	[[document window] setDocEdited:YES];
    return NO;
}

- windowWillClose:sender
{
    if ([[document window] isDocEdited]) 
    	if (NXRunAlertPanel
		  (NULL, "File was edited.", "Save", "Cancel", NULL))
			[self save:self];
    [sender setDelegate:nil];  
    [self free];
    return sender;
}

@end
